from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib import messages
from django.template.context import RequestContext
from django.forms.formsets import formset_factory
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from bootstrap_toolkit.widgets import BootstrapUneditableInput
from django.contrib.auth.decorators import login_required
from .forms import LoginForm, RegisterForm
from mapbf.models  import NewUser
import urlparse
# Create your views here.
def login(request):
	if request.method == 'GET':
		form = LoginForm()
		full_path = request.get_full_path()
		values = urlparse.urlparse(full_path)
		if values[4]:
			return HttpResponseRedirect('/intro/')
		else:
			return render_to_response('intro/login.html', RequestContext(request, {'form':form,}))
	else:
		form = LoginForm(request.POST)
		if form.is_valid():
			username = request.POST.get('username', '')
			password = request.POST.get('password', '')
			user = auth.authenticate(username=username, password=password)
			if user is not None and user.is_active:
				auth.login(request, user)
				return HttpResponseRedirect('/map/')
			else:
				return render_to_response('intro/index.html', RequestContext(request, {'form':form, 'password_is_wrong':True}))
		else:
			return render_to_response('intro/index.html', RequestContext(request, {'form':form, 'password_is_not_valid':True}))

def logout(request):
	auth.logout(request)
	return HttpResponseRedirect('/intro/')

def register(request):
	error=[]
	if request.method == 'POST':
		form = RegisterForm(request.POST)
		if form.is_valid():
			data      = form.cleaned_data
			username  = data['username']
			email     = data['email']
			password  = data['password']
			password2 = data['password2']
			if not NewUser.objects.all().filter(username=username):
				if form.pwd_validate(password, password2):
					user = NewUser.objects.create_user(username, email, password)
					user.save()
					user = auth.authenticate(username=username, password=password)
					if user is not None and user.is_active:
						auth.login(request, user)
						return HttpResponseRedirect('/map/')
				else:
					error.append('Please input the same password')
			else:
				error.append('The username has existed,please change your username')
		else:
			error.append('The form is not valid')
	else:
		form = RegisterForm()
	if error:
		return render_to_response('intro/index.html', {'register_error':error})
	else:
		return render_to_response('intro/register.html',RequestContext(request, {'form':form,'error':error}))